import sys
import pygame

from random import randint
from settings import Settings
from star import Star

class Twinkle_Stars():
    '''管理背景资源以及相关类'''
    
    def __init__(self):
        '''初始化游戏并创建资源'''
        pygame.init()#初始化背景设置，让Pygame能够正常地工作
        self.settings=Settings()

        self.screen=pygame.display.set_mode(
            (self.settings.screen_width,self.settings.screen_height)
        )
        pygame.display.set_caption('一闪一闪亮晶晶')

        self.stars=pygame.sprite.Group()
        self._create_fleet()

    def _check_events(self):
        '''响应按键和鼠标事件'''
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                sys.exit()
    
    def _create_fleet(self):
        '''创建星星群'''
        #创建一个星星并计算一行可容纳多少个星星
        #星星间距为星星宽度
        star=Star(self)
        star_width,star_height=star.rect.size
        available_space_x=self.settings.screen_width-(2*star_width)
        number_stars_x=available_space_x//(2*star_width)

        #计算屏幕可容纳多少行星星
        available_space_y=self.settings.screen_height
        number_rows=available_space_y//(2*star_height)

        #创建外星人群
        for row_number in range(number_rows):
            for star_number in range(number_stars_x):
                star_number=randint(0,number_stars_x)
                row_number=randint(0,number_rows)
                self._create_star(star_number,row_number)

    def _create_star(self,star_number,row_number):
        '''创建一个星星,并将其放在当前行'''
        star=Star(self)
        star_width,star_height=star.rect.size
        star.rect.x=star_width+2*star_width*star_number
        star.rect.y=star_height+2*star_height*row_number
        self.stars.add(star)

    def _update_screen(self):
        '''更新屏幕图像,并切换为新屏幕'''
        self.screen.fill(self.settings.bg_color)
        self.stars.draw(self.screen)
        pygame.display.flip()

    def _run_background(self):
        '''开始运行展示背景图'''
        while True:
            self._check_events()
            self._update_screen()

if __name__=="__main__":
    #创建背景实例并运行背景
    watcher=Twinkle_Stars()
    watcher._run_background()